// pages/HistoricalRecords/HistoricalRecords.js
var that,
  wxCharts = require('../../utils/wxcharts-min.js'),
  api = new (require('../../utils/api.js')),
  headimg = api.getimgurl(),
  app = getApp(),
  util = new (require('../../utils/util.js'));
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list:[],
    tab:0,
    date:'',
    canvasindex:0,
    page:1,
    categories:[],
    datapoint:[],
    minnum:0,
    maxnum:1000,
    navsel:1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that=this;
   
    // that.getline()
  },
  getline(){
    let {categories,datapoint,minnum,maxnum}=that.data
    var windowWidth = '', windowHeight='';    //定义宽高
    try {
      var res = wx.getSystemInfoSync();    //试图获取屏幕宽高数据
      windowWidth = res.windowWidth / 375 * 350;   //以设计图375为主进行比例算换
      windowHeight = res.windowWidth / 375 * 250    //以设计图375为主进行比例算换
    } catch (e) {
      console.error('getSystemInfoSync failed!');   //如果获取失败
    }
    new wxCharts({     //定义一个wxCharts图表实例
      canvasId: 'lineCanvsa',     //输入wxml中canvas的id
      type: 'line',       //图标展示的类型有:'line','pie','column','area','ring','radar'
      categories: categories,    //模拟的x轴横坐标参数
      animation: true,  //是否开启动画
      series: [{   //具体坐标数据
        // name: ' ',  //名字
        data: datapoint,  //数据点
        color:'#FF791F',
        // format: function (val, name) {  //点击显示的数据注释
        //   return val + 'mmHg';
        // }
      },
      ],
      xAxis: {   //是否隐藏x轴分割线
        disableGrid: true,
        fontColor:'#666666',
        gridColor: '#979797',
        axisLabel:{
          show: false,
          interval:2,
          // interArrival:0,
        }
        // opposite : true,
      },
      yAxis: {      //y轴数据
        title: ' ',  //标题
        min: minnum,   //最小值
        max:maxnum,   //最大值
        fontColor:'#333333',
        gridColor: '#979797',
        
      },
      width: windowWidth,  //图表展示内容宽度
      height: windowHeight,  //图表展示内容高度
      dataLabel: false,  //是否在图表上直接显示数据
      dataPointShape: false, //是否在图标上显示数据点标志
     
      legend:false,
      extra: {
        column: {
            width: 30
        }
      },
    });
  },
  //获取历史记录列表
  getdate(){
    wx.showLoading({
      title: '加载中',
    })
    
    let { corpGoodsTag } = app.logininfo
    that.setData({corpGoodsTag})
    let {page,list,navsel}=that.data
    if(navsel=='1'){
      api.oilrecord(page,res=>{
        wx.hideLoading()
        if(res.data.code==0){
          let {nextPage,orderArr}=res.data.entity.data
          if(orderArr.length>0){
            orderArr.forEach(x=>{
              x.date=util.formatTime(new Date(x.addTime*1000))
              let payFee=x.payFee.split(".")
              if(payFee.length==2){
                x.integer=payFee[0]
                x.remainder=payFee[1]
              }else{
                x.integer=payFee[0]
                x.remainder='00'
              }
              list.push(x)
            })
          }
          that.setData({nextPage,list})
        }
      })
    }else{
      api.goodsrecord(page,res=>{
        wx.hideLoading()
        if(res.data.code==0){
          let {nextPage,orderArr}=res.data.entity.data
          if(orderArr.length>0){
            orderArr.forEach(x=>{
              x.date=util.formatTime(new Date(x.addTime*1000))
              let payFee=x.payFee.split(".")
              if(payFee.length==2){
                x.integer=payFee[0]
                x.remainder=payFee[1]
              }else{
                x.integer=payFee[0]
                x.remainder='00'
              }
              list.push(x)
            })
          }
          that.setData({nextPage,list})
        }
      })
    }
  },
   //获取历史记录图表
   getchartdate(){
    wx.showLoading({
      title: '加载中',
    })
    let {date,canvasindex}=that.data,month=date.replace('.','') 
    api.usergather(month,res=>{
      wx.hideLoading()
      if(res.data.code==0){
        let {subConsume,subDiscount,subOilAmount,map}=res.data.entity.data,categories=[],datapoint=[],minnum=0,maxnum=1000,cumulative=0
        if(map.length>0){
          map.forEach((x,i)=>{
            if(i==0){
              minnum=x.num-100
              maxnum=x.num+100
              let day=x.day.replace('/','.')
              categories.push(day)
              datapoint.push(x.num)
              cumulative=Number(x.num)
            }else{
              cumulative+=Number(x.num)
              if(minnum>x.num){
                minnum=x.num-100
              }
              if(maxnum<x.num){
                maxnum=x.num+100
              }
              let day=x.day.replace('/','.')
              if(map.length-1==i){
                categories.push(day)
                datapoint.push(cumulative)
              }else if(i%5==0){
                categories.push(day)
                datapoint.push(cumulative)
              }
            }
          })
          
        }
        if(minnum<0){
          minnum=0
        }
        let total=parseFloat(subConsume)+parseFloat(subDiscount)
        that.drawProgressbg();
        that.drawCircle(subDiscount/(total/2))
        that.setData({subConsume,subDiscount,subOilAmount,canvasindex:canvasindex+1,total,categories,datapoint,maxnum,minnum},()=>{
            that.getline()
        })
      }
    })
  },
  // 切换tab
  clicktab(e){
    let {code}=e.currentTarget.dataset,{tab}=that.data
    if(tab==code)return;
    if(code==1){
      that.setData({tab:code},()=>{
        that.getchartdate()
      })
      // let {totaldiscount,newtotalprice,canvasindex}=that.data
      // let total=Number(newtotalprice)+Number(totaldiscount)
      // that.setData({canvasindex:canvasindex+1},()=>{
      //   that.drawProgressbg();
      //   that.drawCircle(totaldiscount/(total/2))
      // })
      // that.setData({tab:code})
      // that.getline()
    }else{
      that.setData({tab:code,page:1,list:[]},()=>{
        that.getdate()
      })

    }
  },
  drawProgressbg(){
    let {canvasindex}=that.data
    // 使用 wx.createContext 获取绘图上下文 context
    var ctx = wx.createCanvasContext('canvasProgressbg'+canvasindex)
    ctx.setLineWidth(4);// 设置圆环的宽度
    ctx.setStrokeStyle('#F6F7FB'); // 设置圆环的颜色
    ctx.setLineCap('round') // 设置圆环端点的形状
    ctx.beginPath();//开始一个新的路径
    ctx.arc(90, 90, 80, 0, 2 * Math.PI, false);
    //设置一个原点(100,100)，半径为90的圆的路径到当前路径
    ctx.stroke();//对当前路径进行描边
    ctx.draw();
  },
  drawCircle: function (step){  
    let {canvasindex}=that.data
    var context = wx.createCanvasContext('canvasProgress'+canvasindex);
      // 设置渐变
      var gradient = context.createLinearGradient(200, 100, 100, 200);
      gradient.addColorStop("0", "#2661DD");
      gradient.addColorStop("0.5", "#40ED94");
      gradient.addColorStop("1.0", "#5956CC");
      context.setLineWidth(10);
      context.setStrokeStyle(gradient);
      context.setLineCap('round')
      context.beginPath();
      // 参数step 为绘制的圆环周长，从0到2为一周 。 -Math.PI / 2 将起始角设在12点钟位置 ，结束角 通过改变 step 的值确定
      context.arc(90, 90, 80,  -Math.PI / 2, step * Math.PI - Math.PI / 2, false);
      context.stroke();
      context.draw()
  },
  toproposal(){
    wx.navigateTo({
      url: '../proposal/proposal',
    })
  },
  pickchange(e){
    console.log(e.detail.value,'eeeeeeeee');
    let date=e.detail.value.replace('-','.')
    that.setData({date},()=>{
      that.getchartdate()
    })
  },
  //取消订单
  cancelorder(e){
    wx.showModal({
      content: '确认要取消订单吗？',
      success (res) {
        if (res.confirm) {
          api.oilcancel(e.currentTarget.dataset.orderid,res=>{
            if(res.data.code==0){
              wx.showToast({
                title: '取消订单成功',
                icon: 'none',
                duration:1000,
              })
              setTimeout(function () {
                that.setData({page:1,list:[]},()=>{
                  that.getdate()
                })
              },1000)
            }else{
              wx.showToast({
                title: '取消订单失败',
                icon: 'none',
                duration:1000,
              })
            }
          })
        } else if (res.cancel) {
          // console.log('用户点击取消')
        }
      }
    })
    
    
  },
  navsel(e){
    let {code}=e.currentTarget.dataset
    console.log(code,'codecode');
    that.setData({navsel:code,page:1,list:[]},()=>{
      that.getdate()
    })
  },
 /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // let {totaldiscount,newtotalprice}=that.data
    // that.drawProgressbg();
    // let total=Number(newtotalprice)+Number(totaldiscount)
    // that.drawCircle(totaldiscount/(total/2))
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let year=new Date().getFullYear(),newmonth=new Date().getMonth()+1,
    newdate=util.formatTime(new Date()),{tab}=that.data
    if(newmonth<10)newmonth='0'+newmonth
    let date=year+"."+newmonth
    that.setData({date,newdate,list:[]},()=>{
      that.getdate()
    })
    if(tab==1){
      that.getchartdate()
    }
  },
  to(e){
    let {url}=e.currentTarget.dataset
    wx.navigateTo({
      url: `../${url}/${url}`,
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    let {canvasindex}=that.data
    that.setData({canvasindex:canvasindex+1})

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let {tab,page,nextPage}=that.data
    if(tab==0&&nextPage==1){
      page=page+1
      that.setData({page},()=>{
        that.getdate()
      })
    }

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})